import { BlockNoteView } from "@blocknote/shadcn";
import {
  createReactInlineContentSpec,
  SuggestionMenuController,
  useCreateBlockNote,
  type DefaultReactSuggestionItem
} from "@blocknote/react";
import "@blocknote/shadcn/style.css";
import { zh } from "@blocknote/core/locales";
import {
  BlockNoteSchema,
  defaultBlockSpecs,
  defaultInlineContentSpecs,
  defaultStyleSpecs,
  filterSuggestionItems
} from "@blocknote/core";

const schema = BlockNoteSchema.create({
  blockSpecs: {
    ...defaultBlockSpecs
  },
  inlineContentSpecs: {
    ...defaultInlineContentSpecs,
    mention: createReactInlineContentSpec(
      {
        type: "mention",
        content: "none",
        propSchema: {
          id: {
            default: ""
          },
          name: {
            default: ""
          }
        }
      },
      {
        render: props => {
          const { id } = props.inlineContent.props;
          return <span className="text-blue-500 bg-amber-200">@{id}</span>;
        }
      }
    )
  },
  styleSpecs: {
    ...defaultStyleSpecs
  }
});

export function DocEditorDemo() {
  const editor = useCreateBlockNote({
    schema,
    dictionary: zh,
    initialContent: [
      {
        type: "paragraph",
        content: [
          {
            type: "text",
            text: "这是一段测试段落，包括一个提及内容",
            styles: {}
          },
          {
            type: "mention",
            props: { id: "User123", name: "用户123" }
          }
        ]
      }
    ]
  });

  const getMentionUserItems = (e: typeof editor) => {
    const userItems: DefaultReactSuggestionItem[] = [
      {
        icon: <span>👤</span>,
        title: "用户123",
        onItemClick: () => {
          e.insertInlineContent([
            {
              type: "mention",
              props: { id: "User123", name: "用户123" }
            }
          ]);
        }
      },
      {
        icon: <span>👤</span>,
        title: "渡一用户123",
        onItemClick: () => {
          e.insertInlineContent([
            {
              type: "mention",
              props: { id: "User123", name: "用户123" }
            }
          ]);
        }
      }
    ];
    return userItems;
  };

  return (
    <BlockNoteView editor={editor}>
      <SuggestionMenuController
        triggerCharacter="@"
        getItems={async query => {
          return filterSuggestionItems(getMentionUserItems(editor), query);
        }}
      />
    </BlockNoteView>
  );
}
